#include <iostream>
#include <algorithm>
#include <memory>
#include "TcpServer.hpp"
#include "log.hpp"
#include "demon.hpp"
#include"TransLate.hpp"
using namespace std;
TranSlate trans;
void Interact(int sockfd, std::string &out, const std::string &in)
{
    char buffer[1024];
    int n = read(sockfd, buffer, sizeof(buffer)) - 1;
    if (n > 0)
    {
        buffer[n] = 0;
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0)
    {
        lg.massage(Info, "client quit...\n");
    }
    else
    {
        lg.massage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
    }
}
void Ping(int sockfd, InetAddr addr)
{
    lg.massage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "ping", sockfd);
    string inbuffer;
    Interact(sockfd, inbuffer, "pong");
}
void Transform(int sockfd, InetAddr addr)
{
    lg.massage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "Transform", sockfd);
    char message[128];
    int n = read(sockfd, message, sizeof(message) - 1); // tcp中要正确的读取，必须结合用户协议！！
    if (n > 0)
        message[n] = 0;
    std::string messagebuf = message;

    std::transform(messagebuf.begin(), messagebuf.end(), messagebuf.begin(), [](unsigned char c)
                   { return std::toupper(c); });
    write(sockfd, messagebuf.c_str(), messagebuf.size());
}
void Translate(int sockfd, InetAddr addr)
{
      lg.massage(Debug, "%s select %s success, fd : %d\n", addr.PrintDebug().c_str(), "Translate", sockfd);
      char wordbuffer[128];
      int n=read(sockfd,wordbuffer,sizeof(wordbuffer));
      if(n>0)
      {
        wordbuffer[n]=0;
        string chinese=trans.Excute(wordbuffer);
        write(sockfd,chinese.c_str(),chinese.size());
       lg.massage(Debug, "%s Translate service, %s->%s\n", addr.PrintDebug().c_str(), wordbuffer, chinese.c_str());
}
      }
void useage(string proc)
{
    cout << "Usage:\n\t" << proc << " "
         << "local_port" << endl;
}
int main(int arg, char *argv[])
{
    if (arg != 2)
    {
        useage(argv[0]);
        return 1;
    }
    //demons(false,false);
    uint16_t port = stoi(argv[1]);
    std::unique_ptr<TcpServer> tsvr = make_unique<TcpServer>(port);
    tsvr->RegisterFunc("ping", Ping);
    tsvr->RegisterFunc("transform", Transform);
    tsvr->RegisterFunc("translate", Translate);
    tsvr->Init();
    tsvr->Start();
    return 0;
}